package com.jse.web;

import com.jse.Fs;
import com.jse.Js;
import com.jse.Jse;

public class JsRoute implements Route {

	@Override
	public Object run(Ctx tbl) throws Exception {
		String path=tbl.getPath();
		String suffix=tbl.getSuffix();
		Object obj=null;
		if("".equals(suffix)) {
			String url=tbl.getMapping();
			String mappingjs=url+".js";
			String pathvue=url.concat(".vue");
			String pathhtml=url.concat(".html");
			if(Fs.exists("js",mappingjs)){//js
				obj=Js.run(Jse.jspath()+mappingjs,tbl);
				if(tbl.getAttribute("obj")==null)tbl.setAttribute("obj",obj);
				if(tbl.isJson()) {
					View.json.render(tbl,obj);
				}else {
					View.ret.render(tbl,obj);
				}
			}else if(Fs.exists("js",pathvue)){//vue
				if(Fs.exists("js","vue.html")) {
					View.tpl.render(tbl,"vue.html");
				}else {
					View.text.render(tbl,Fs.readString("js",url+".vue"));
				}
			}else if(Fs.exists("js",pathhtml)){//html
				obj=Js.evalVue(Jse.jspath()+pathhtml, tbl);
				View.html.render(tbl, obj);
			}else if(Fs.exists("web",pathvue)){//vue
				if(Fs.exists("js","vue.html")) {
					View.tpl.render(tbl,"vue.html");
				}else {
					View.text.render(tbl,Fs.readString("web",url+".vue"));
				}
			}else if(Fs.exists("web", url+".html")) {
				View.tpl.render(tbl,url+".html");
			}else {
				View.not.render(tbl,"404");
			}
			
		}else if("html".equals(suffix)){
			String url=tbl.getMapping();
			String mappingjs=url+".js";
			if(Fs.exists("js",mappingjs)){
				obj=Js.run(Jse.jspath()+mappingjs,tbl);
				if(tbl.getAttribute("obj")==null)tbl.setAttribute("obj",obj);
			}
			View.tpl.render(tbl,tbl.getPath());
		}else if(Web.STATIC_SUFFIX.contains(suffix)){
			View.staticforward.render(tbl,path);
		}else {
		switch (suffix) {
		case "vue","jsx" ->//静态
			View.text.render(tbl,Js.evalVue(Jse.webapp()+path,tbl));
		case "py" ->//TODO py脚本 
			View.text.render(tbl,Fs.readString("web",path));
		case "json" ->{
			String mappingjs=tbl.getMapping()+".js";
			if(Fs.exists("web",path))View.json.render(tbl,Fs.readString("web", path));
			else if(Fs.exists("jspath",mappingjs)) {
			 View.json.render(tbl,Js.run(Jse.jspath()+mappingjs,tbl));
			}else View.json.render(tbl,"{\"code\":404}");
		}
		case "html" ->{
			View.tpl.render(tbl,path);
		}
		default ->{
			System.out.println("not exec static_url:"+path);
			View.staticforward.render(tbl,path);
		}
		}
		}
		return false;
	}

	
}
